import { defineStore } from 'pinia';
// 操作本地存储token的方法
import { getToken, removeToken, setToken } from '../utils/token-utils';
// 定义state返回类型
import type { UserInfoState } from './interface';
import {ElMessage} from 'element-plus'
import {staticRoutes} from '@/router/routes'
import { reqLoginOut, reqUserInfo, reqUserLogin } from '@/api/user';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
// 选项式写法
export const useUserInfoStore = defineStore('userInfo', {
  // state是函数   state： () => {} ，定义state返回类型UserInfoState
	state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: []
  }),

	actions: {
    async login (username:string, password:string) {
      const result = await reqUserLogin({username, password})
      // console.log(result)
      //存入仓库
      this.token = result.token
      //持久化存储
      setToken(result.token)
    },
    //获取用户信息
    async getInfo () {
      const result = await reqUserInfo()
      // console.log(result)
      this.name = result.name
      this.avatar = result.avatar
      this.menuRoutes = staticRoutes//路由表的静态路由
    },

    async reset () {
      //退出请求
      await reqLoginOut()
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.name = ''
      this.avatar = ''
    },
	},
});
